<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "post_attr".
 *
 * @property string $id
 * @property string $post_id
 * @property string $attr_id
 * @property string $name
 * @property string $val
 *
 * @property Attributes $attr
 */
class PostAttr extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'post_attr';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['post_id', 'attr_id'], 'integer'],
            [['name'], 'required'],
            [['val'], 'string'],
            [['name'], 'string', 'max' => 64],
            [['attr_id'], 'exist', 'skipOnError' => true, 'targetClass' => Attributes::className(), 'targetAttribute' => ['attr_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'post_id' => '内容id',
            'attr_id' => '属性id',
            'name' => '属性名称',
            'val' => '属性值',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAttr()
    {
        return $this->hasOne(Attributes::className(), ['id' => 'attr_id']);
    }

    /**
     * 保存内容属性值
     * @param int $post_id 内容id
     */
    public static function saveFromPost($post_id)
    {
        //保存前清除原有的数据
        static::deleteAll("post_id=:post_id", [":post_id" => $post_id]);
        $attrs = Yii::$app->request->post('Attr');
        if ($attrs) {
            foreach ($attrs as $ak => $av) {
                $model = new PostAttr();
                $model->post_id = $post_id;
                $model->name = $ak;
                foreach ($av as $ak2 => $av2) {
                    $model->attr_id = $ak2;
                    $model->val = $av2;
                }
                $model->save();
            }
        }
    }

    /**
     * 返回内容属性值
     * @param int $post_id 内容id
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getPostAttr($post_id)
    {
        return static::find()->select("attr_id,name,val")->where("post_id=$post_id")->asArray()->all();
    }
}
